﻿using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeGenerator.Common
{
    internal class ZipUtil
    {
        /// <summary>
        /// 压缩文件夹
        /// </summary>
        /// <param name="dirPath"></param>
        /// <param name="outStream"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static dynamic ZipDir(string dirPath, ZipOutputStream outStream, string pwd = null)
        {
            try
            {
                DirectoryInfo dirInfo = new DirectoryInfo(dirPath);
                if (!string.IsNullOrWhiteSpace(pwd))
                {
                    outStream.Password = pwd;
                }
                //文件夹处理
                List<string> dirs = dirInfo.GetDirectories("*", SearchOption.AllDirectories).Select(s => s.FullName.Replace(dirInfo.FullName, "") + "\\").ToList();
                foreach (string dir in dirs)
                {
                    ZipEntry ZipEntry = new ZipEntry(dir);
                    outStream.PutNextEntry(ZipEntry);
                    outStream.Flush();
                }

                //文件处理
                List<string> files = dirInfo.GetFiles("*", SearchOption.AllDirectories).Select(s => s.FullName).ToList();

                foreach (string file in files)
                {
                    using (FileStream fs = File.OpenRead(file))
                    {
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);

                        ZipEntry ZipEntry = new ZipEntry(file.Replace(dirInfo.FullName, ""));
                        outStream.PutNextEntry(ZipEntry);
                        outStream.Write(buffer, 0, buffer.Length);
                        outStream.Flush();
                    }
                }
                return new { result = true, msg = "Success" };
            }
            catch (Exception ex)
            {
                return new { result = true, msg = "Error:" + ex.Message };
            }
        }
    }
}
